package com.wyx.httpService.shanxitobaccoService.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wyx.annotation.MethodEventDescription;
import com.wyx.httpService.shanxitobaccoService.OrderShanxiTobaccoCrawlerService;
import com.wyx.pojo.Smoke;
import com.wyx.pojo.httpSmokeBean.shanxitobaccobean.request.SmokeInfoBean;
import com.wyx.pojo.httpSmokeBean.shanxitobaccobean.response.*;
import com.wyx.pojo.constant.Info;
import com.wyx.service.SmokeService;
import com.wyx.utils.commonUtil.CUtil;
import com.wyx.utils.shanxitobaccoUtil.SUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * @author 吴宇~
 * @motto 我亦无他，唯手熟尔。
 * @edition jdk1.8
 * @reflection 0-1 喧闹任其喧闹，自由我自为之，我自风情万种，与世无争。
 * @date 2024/04/04/11:56
 * @target 心若有所向往，何惧道阻且长
 */
@Service
@Slf4j
public class OrderShanxiTobaccoCrawlerServiceImpl implements OrderShanxiTobaccoCrawlerService {
    @Autowired
    private SmokeService smokeService;
    @Autowired
    private SmokeInfoShanxiTobaccoCrawlerServiceImpl smokeInfoShanxiTobaccoCrawlerService;

    /**
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return 查询指定时间的订单，时间跨度最长为三个月，开始时间最早是2023年10月5日
     */
    @Override
    @MethodEventDescription(event = "Query order list")
    public OrderInfo selectOrderListByDate(String startTime, String endTime) {
//        第一次查询，第一页
        OrderInfo orderInfo = sendRequestGetOrderList(startTime, endTime, 1);
        if (orderInfo == null) {
            log.info("没有查询到订单信息，cookie信息过期了？还是  没联网呢？？？");
        }
        List<Bill> rows = orderInfo.getRows();
        int result = (Integer.parseInt(orderInfo.getTotal()) + 4 - 1) / 4; // 将x除以16并向上取整
//        之后查询从第二页开始
        for (int i = 0; i < result - 1; i++) {
            OrderInfo orderInfo1 = sendRequestGetOrderList(startTime, endTime, i + 2);
            rows.addAll(orderInfo1.getRows());
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return orderInfo;
    }

    /**
     * 根据订单id查询订单的csv文件
     *
     * @param order_uuid 订单id
     * @return 返回订单的csv文件
     */
    @Override
    @MethodEventDescription(event = "Download latest order file (csv)", isShowAllArg = true)
    public byte[] selectOrderDetailCSVFileByOrderId(String order_uuid) {
        OkHttpClient client = new OkHttpClient();
        byte[] bytes = new byte[0];
        SmokeInfoBean smokeInfoBean = new SmokeInfoBean().init5(order_uuid);
        String wppm = SUtil.encipher(CUtil.obgToJson(smokeInfoBean));
        //https://sx.jinye.cn
//        String url = "https://shanxitobacco.com/wdk?action=ecw.page&method=export_excel&wppm=" + wppm;
        String url = "https://sx.jinye.cn/wdk?action=ecw.page&method=export_excel&wppm=" + wppm;
        Request request = CUtil.setCookie(new Request.Builder(), Info.ShanxiTobaccoCookieMap)
                .url(url)
                .build();
        try {
            Response response = client.newCall(request).execute();
            bytes = response.body().bytes();
            CUtil.set_SetCookie(response.headers(), Info.ShanxiTobaccoCookieMap);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytes;
    }

    /**
     * 得到所有订购的烟。根据这些信息将barcode2  字段填充到数据库
     */
    @Override
    public void fillBarCode() {
//        发送http请求，返回信息，根据productUUID字段进行对应，将查询到的 bar_code2  字段添加到smoke数据库的 bar_code
        List<ProdLimitInfos> prod_limit_infos = smokeInfoShanxiTobaccoCrawlerService.selectAvailableAmount().getProd_limit_infos();
        List<Smoke> list = smokeService.list(new LambdaQueryWrapper<Smoke>().select(Smoke::getId, Smoke::getProductUuid));

        /**
         * TODO：
         * 这样优化 有些僵硬了。  或者将其中的一个转换为map另外一个使用  stream
         *  list.forEach(smoke -> {
         *             prod_limit_infos.stream()
         *                     .filter(prodLimitInfosSmoke -> smoke.getProductUuid().equals(prodLimitInfosSmoke.getProduct_uuid()))
         *                     .findFirst()
         *                     .ifPresent(prodLimitInfosSmoke -> smoke.setBarCode(prodLimitInfosSmoke.getBar_code2()));
         *         });
         */


        for (int i1 = 0; i1 < list.size(); i1++) {
            for (int i = 0; i < prod_limit_infos.size(); i++) {
                ProdLimitInfos prodLimitInfosSmoke = prod_limit_infos.get(i);
                if (list.get(i1).getProductUuid().equals(prodLimitInfosSmoke.getProduct_uuid())) {
                    list.get(i1).setBarCode(prodLimitInfosSmoke.getBar_code2());
                }
            }
        }
        smokeService.updateBatchById(list);
    }

    /**
     * 发送请求获取订单集合  根据起止时间第几页
     *
     * @param startTime
     * @param endTime
     * @param page
     * @return
     */
    private OrderInfo sendRequestGetOrderList(String startTime, String endTime, Integer page) {
        OkHttpClient client = new OkHttpClient();
//        https://sx.jinye.cn/wdk?action=ecw.page&method=call_service&ajaxparamtime=1728873140411
//        String url = "https://shanxitobacco.com/wdk?action=ecw.page&method=call_service&ajaxparamtime=" + System.currentTimeMillis();
        String url = "https://sx.jinye.cn/wdk?action=ecw.page&method=call_service&ajaxparamtime=" + System.currentTimeMillis();
        String wppm = SUtil.encipher(CUtil.obgToJson(new SmokeInfoBean().init4(startTime, endTime, page)));
        OrderInfo orderInfo = null;
        FormBody formBody = new FormBody.Builder()
                .add("wppm", wppm)
                .build();
        Request.Builder builder = CUtil.setCookie(new Request.Builder(), Info.ShanxiTobaccoCookieMap);
        Request request = builder
                .url(url)
                .post(formBody)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            orderInfo = CUtil.jsonToObj(string, OrderInfo.class);
            CUtil.set_SetCookie(response.headers(), Info.ShanxiTobaccoCookieMap);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return orderInfo;
    }
}
